package com.wulis.provider.authority.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wulis.common.model.enums.DeletedStateEnum;
import com.wulis.common.support.BaseServiceImpl;
import com.wulis.provider.authority.mapper.AccountRoleMapper;
import com.wulis.provider.authority.model.entity.AccountRole;
import com.wulis.provider.authority.service.AccountRoleService;

import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

/**
 * 权限管理:账号-角色表 Service实现类
 *
 * @author WuliBao
 * @date 2020-04-17
 */
@Slf4j
@Service
@AllArgsConstructor
public class AccountRoleServiceImpl extends BaseServiceImpl<AccountRoleMapper, AccountRole>
    implements AccountRoleService {
    private final AccountRoleMapper accountRoleMapper;
    
    /**
     * WEB:新增用户角色关联关系
     * 
     * @param accountId accountId
     * @param roleIds roleIds
     * @return return
     */
    @Override
    public int insertAccountRole(@NonNull Long accountId, @NonNull List<Long> roleIds) {
        if (roleIds.isEmpty()) {
            return 0;
        }
        List<AccountRole> accountRoles = roleIds.stream()
            .map(roleId -> new AccountRole().setAccountId(accountId).setRoleId(roleId))
            .collect(Collectors.toList());
        return accountRoleMapper.insertBatchDuplicateKeyUpdate(accountRoles);
    }
    
    /**
     * WEB:修改用户角色关联关系
     *
     * @param accountId accountId
     * @param roleIds roleIds
     * @return int
     */
    @Override
    public int updateAccountRole(@NonNull Long accountId, @NonNull List<Long> roleIds) {
        // 删除用户角色关联关系
        deleteAccountRole(accountId);
        // 新增用户角色关联关系
        return insertAccountRole(accountId, roleIds);
    }
    
    /**
     * WEB:删除用户角色关联关系
     *
     * @param accountId accountId
     * @return int
     */
    @Override
    public int deleteAccountRole(@NonNull Long accountId) {
        UpdateWrapper<AccountRole> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(AccountRole::getAccountId, accountId);
        AccountRole accountRole = new AccountRole();
        accountRole.setDeleted(DeletedStateEnum.IS_DELETED.value());
        return accountRoleMapper.update(accountRole, wrapper);
    }
}
